package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"xinhua_book/cache"
	"xinhua_book/models"
)

type LikeController struct {
	beego.Controller
}

func (c *LikeController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	var count int64
	models.DB.Model(&models.Like{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size

	var bookId []interface{}
	userId, _ := c.GetInt("user_id")
	models.DB.Model(&models.Like{}).Select("book_id").Where("user_id = ?", userId).Find(&bookId)

	var like []models.Book
	cacheData := cache.Rdb.Get(cache.Ctx, "like_list").Val()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Where("id in (?)", bookId).Find(&like)
		jsonData, _ := json.Marshal(like)
		cache.Rdb.Set(cache.Ctx, "like_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &models.Like{})
		c.Data["json"] = map[string]interface{}{
			"code":    200,
			"msg":     "展示成功",
			"data":    like,
			"page":    page,
			"size":    size,
			"count":   count,
			"sumpage": sumpage,
		}
		c.ServeJSON()
	}
}

func (c *LikeController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var bookId []interface{}
	userId, _ := c.GetInt("user_id")
	models.DB.Model(&models.Like{}).Select("book_id").Where("user_id = ?", userId).Find(&bookId)
	var like []models.Book
	err := models.DB.Delete(&models.Like{}, userId).Where("id in (?)", bookId).Find(&like).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "已阅读的记录无法删除",
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "删除成功",
		}
		c.ServeJSON()
	}
}
